package com.ovopark.service

import android.app.Service
import android.content.Intent
import android.os.Build
import androidx.annotation.RequiresApi
import com.ovopark.firecar.R
import com.ovopark.firecar.utils.NotificationUtils

/**
 * Created by cz on 2018/8/16.
 */
abstract class BaseNotificationService : Service() {
    override fun onCreate() {
        super.onCreate()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            createNotificationChannel()
        }
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            createNotificationChannel()
        }
        onServiceStartCommand(intent, flags, startId)
        return START_STICKY
    }

    override fun onDestroy() {
        super.onDestroy()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            stopForeground(true)
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private fun createNotificationChannel() {
        val notificationUtils = NotificationUtils(this)
        notificationUtils.createNotificationChannel()
        val builder = notificationUtils.getChannelNotification(
            getString(R.string.app_name),
            getString(R.string.running)
        )
        val id = serviceChannelId
        startForeground(if (id > 0) id else 1, builder.build())
    }

    protected abstract fun onServiceStartCommand(intent: Intent?, flags: Int, startId: Int)
    protected abstract val serviceChannelId: Int
}